package model;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;

public class File {

	private String path;

	public File(String path) {
		this.path = path;
	}

	/**
	 * Opens a serialized collections of players object
	 * 
	 * @return collection of players if a file is non existing then it is created
	 */
	@SuppressWarnings("unchecked")
	public ArrayList<Player> LoadFile() {
		
		ArrayList<Player> players = new ArrayList<Player>();
		ObjectInputStream load = null;
		
		try {
			FileInputStream loadFile = new FileInputStream(path);

			load = new ObjectInputStream(loadFile);

			players = (ArrayList<Player>) load.readObject();

			//load.close();
		} catch (FileNotFoundException e) {
			try {
				System.out.println("No file found, creating empty list.");
				Files.createFile(Paths.get(path)); // Creates an empty file
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (Exception exc) {
			exc.printStackTrace(); // If there was an error, print the info.
		}finally{
			try {
				load.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return players;
	}

	/**
	 * saves a collection of players to the path
	 * 
	 * @param players
	 * @return
	 */
	public boolean SaveFile(Blackjack game) {
		boolean success = false;
		ArrayList<Player> players=game.getPlayers();
		try {
			FileOutputStream saveFile = new FileOutputStream(path);

			ObjectOutputStream save = new ObjectOutputStream(saveFile);

			save.writeObject(players);

			save.close();
			success = true;
		} catch (Exception exc) {
			exc.printStackTrace();
		}

		return success;
	}

}